package com.aabte.servlet;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value = "/async", asyncSupported = true)
public class HelloAsyncServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("主线程开始处理...");

        // 1. 开启异步模式
        AsyncContext asyncContext = req.startAsync();

        // 2. 执行业务逻辑处理
        asyncContext.start(new Runnable() {
            @Override
            public void run() {

                try {
                    System.out.println(Thread.currentThread() + " start...");

                    sayHello();

                    System.out.println(Thread.currentThread() + " end...");

                    AsyncContext asyncContext1 = req.getAsyncContext();
                    ServletResponse response = asyncContext1.getResponse();
                    response.getWriter().write("hello async...");
                    asyncContext.complete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        System.out.println("主线程处理结束...");

    }

    private void sayHello(){
        try {
            System.out.println(Thread.currentThread() + " processing...");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
